package com.hua.api.modules.huawa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hua.api.core.activemq.ActiveMqConstant;
import com.hua.api.core.activemq.MqMessageBuilder;
import com.hua.api.core.activemq.consumer.event.EventConstant;
import com.hua.api.core.framework.http.response.OpenApiResponse;
import com.hua.api.core.framework.util.Result;
import com.hua.api.core.framework.util.exception.ApiError;
import com.hua.api.core.out.huawa.HuawaHelper;
import com.hua.api.core.out.huawa.request.AccountBalancesRequest;
import com.hua.api.core.out.huawa.request.CreateOrderRequest;
import com.hua.api.core.constants.Status;
import com.hua.api.core.out.huawa.request.GetCourieInfoRequest;
import com.hua.api.core.out.huawa.request.SelectStoreListRequest;
import com.hua.api.core.util.StringUtil;
import com.hua.api.core.util.ValidationUtil;
import com.hua.api.modules.home.service.ActiveMqService;
import com.hua.api.modules.huawa.dao.HuawaOrderInfoDao;
import com.hua.api.modules.huawa.domain.HuawaOrderInfo;
import com.hua.api.modules.huawa.service.HuawaService;
import com.hua.api.modules.huawa.vo.HuawaOrderInfoVo;
import com.hua.api.modules.order.dao.OrderInfoDao;
import com.hua.api.modules.order.domain.OrderInfo;
import com.hua.api.modules.order.domain.OrderItems;
import com.hua.api.modules.order.service.OrderInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class HuawaServiceImpl implements HuawaService {


    private final OrderInfoDao orderInfoDao;

    private final HuawaOrderInfoDao huawaOrderInfoDao;

    private final OrderInfoService orderInfoService;

    private final ActiveMqService activeMqService;

    @Override
    public Result accountBalances() {
        AccountBalancesRequest request = new AccountBalancesRequest();
        return request.getResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderCreate(String orderNo, HuawaOrderInfoVo vo) {
        ValidationUtil.requireNotNull(vo.getOrderAmount(),"请输入转单价！");
        OrderInfo orderInfo = orderInfoDao.findOrderInfoWithOrderNo(orderNo);
        ValidationUtil.requireNotNull(orderInfo,"OrderInfo","orderNo",orderNo);
        if(StringUtil.equals(orderInfo.getChannel(),Status.CHANNEL_HUAWA)){
            throw ApiError.Type.CHANNEL_API_ERROR.toException();
        }
        String isPayment = StringUtil.dealEmpty(vo.getIsPayment(), Status.LOGIC_TRUE);
        List<OrderItems> list = orderInfoDao.queryOrderItems(orderInfo.getId());
        HuawaOrderInfo huawaOrderInfo = HuawaHelper.transHuawaOrderInfo(orderInfo,list,vo.getOrderAmount(),isPayment);
        CreateOrderRequest request = HuawaHelper.getCreateOrderRequest(huawaOrderInfo);

        // JSONObject data = JSONObject.parseObject(JSONObject.toJSON(huawaOrderInfo).toString());
        //  花娃导入订单={"result":1,"data":{"order_sta":22,"is_check":1,"order_id":38543073,"order_sn":"20250116-170937-20379"}}

		OpenApiResponse response = request.doRequest();
		if(!response.isError){
			log.info("花娃导入订单={}",response.toJSONObject());
			JSONObject result = response.toJSONObject();
			if(result.getInteger("result")==1){
                String orderId=result.getJSONObject("data").getString("order_id");
                String isCHeck = result.getJSONObject("data").getString("is_check"); // 是否是待发布 1：是 2：不是
                String status=result.getJSONObject("data").getString("order_sta");
                // String orderSn=result.getJSONObject("data").getString("order_sn");
                String orderSn=result.getJSONObject("data").getString("order_sn");
                huawaOrderInfo.setHuawaOrderId(orderId);
                huawaOrderInfo.setIsCheck(isCHeck);
                huawaOrderInfo.setStatus(status);
                huawaOrderInfo.setHuawaOrderSn(orderSn);

                // 更新处理渠道为 "花娃"
                orderInfo.setChannel(Status.CHANNEL_HUAWA);
                orderInfoDao.updateObject(orderInfo);

                orderInfoDao.saveObject(huawaOrderInfo);
            }else{
			    throw ApiError.Type.BENLAI_API_ERROR.toException("发布花娃订单失败");
            }

		}else {
            log.error("花娃导入订单失败 huawaService.orderCreate={}",response.errMsg);
            throw ApiError.Type.BENLAI_API_ERROR.toException("发布花娃订单失败");

		}


    }

    /**
     *
     HuaWaController.receive body=
     {"status":1,"data":
     { "push_content":"\u8ba2\u535520250116-170937-20379\uff0c\u5df2\u7ecf\u53d6\u6d88",
     "api_notify_url":"http:\/\/api.hua1000.com.cn\/api\/huawa\/receive",
     "wd_notify_url":"",
     "order_id":38543073,
     "order_sn":"20250116-170937-20379",
     "order_state":"CANCEL_ORDER",
     "order_amount":"60.00",
     "pay_amount":"60.00",
     "seller_order":"911737018282159003",
     "order_type":"2",
     "return_cancel_info": {"cancel_time":"1737019075"},
     "sign_data":"DCE0B1CC42A41CDF4BADF1645ECE43C2"
     }
     }
     *
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onHuawaReceive(JSONObject data) {
        log.info("花娃状态回调 HuawaServiceImpl.onHuawaReceive={}",data.toJSONString());
        String order_state = data.getString("order_state");
        Status.HuawaStatus huawaStatus = Status.HuawaStatus.fromValue(order_state);
        if(null!=huawaStatus){
           log.info("花娃状态回调  status={}",huawaStatus.getName());
           String orderId = data.getString("order_id");
           HuawaOrderInfo huawaOrderInfo = huawaOrderInfoDao.findOrderInfoWithOrderNo(orderId);
           if(huawaOrderInfo!=null){
               if(huawaStatus==Status.HuawaStatus.CANCEL_ORDER){
                   // 订单取消
                   log.info("花娃订单取消 orderId={}",orderId);

               }else if(huawaStatus == Status.HuawaStatus.STORE_SEND_IMG){
                   log.info("花娃订单上传审核图 data={}",data.toJSONString());

               }else if(huawaStatus == Status.HuawaStatus.ORDER_STORE_PRICE){

                   log.info("花娃订单花店报价 data={}",data.toJSONString());
                   onOrderStorePrice(huawaOrderInfo);

               }else if(huawaStatus == Status.HuawaStatus.ORDER_FINISH){
                   log.info("花娃订单完成 data={}",data.toJSONString());
                   // 订单完成
                   orderInfoService.onOrderInfoFinish(huawaOrderInfo.getOrderNo());

               }else if(huawaStatus == Status.HuawaStatus.START_DELIVERY_ORDER){
                   log.info("花娃订单开始配送 data={}",data.toJSONString());
                   //
                   onStartDeliveryOrder(huawaOrderInfo);

               }else if(huawaStatus == Status.HuawaStatus.ORDER_ACHIEVE){
                   log.info("花娃订单已送达 data={}",data.toJSONString());
                   //
                    orderInfoService.onOrderInfoSendSongda(huawaOrderInfo.getOrderNo());
               }else if(huawaStatus == Status.HuawaStatus.STORE_CANCEL_ORDER){
                   log.info("花娃订单花店撤单 data={}",data.toJSONString());


               }else if(huawaStatus == Status.HuawaStatus.STORE_ACCEPT_ORDER){

                   // 成交价
                   Double dealPrice = data.getDouble("pay_amount");
                   String storeAddress = null; // 店铺地址
                   String storeMobile = null; // 手机号
                   String storeName = null;
                   if(data.containsKey("return_store_info")){
                       JSONObject storeInfo = data.getJSONObject("return_store_info");
                       storeAddress = storeInfo.getString("store_addr_info");
                       storeMobile = storeInfo.getString("store_mobile");
                       storeName = storeInfo.getString("store_name");
                   }

                   log.info("花店接单 订单号={} 成交价={}  店铺={} 地址={}",huawaOrderInfo.getOrderNo(),dealPrice,storeName,storeAddress);
                   orderInfoService.onStoreAcceptOrder(huawaOrderInfo.getOrderNo(),storeAddress,storeName,storeMobile);

                   huawaOrderInfo.setDealPrice(dealPrice);

                   /**
                    {
                        "api_notify_url":"http://api.hua1000.com.cn/api/huawa/receive",
                        "seller_order":"",
                        "sign_data":"04486B032CA30E2BD11E380F212D381F",
                        "order_amount":"130.00",
                        "pay_amount":"130.00",
                        "push_content":"订单20250508-152334-31583，已经被【宁津极速鲜花店】接收",
                        "wd_notify_url":"",
                        "order_id":40861652,
                        "order_state":"STORE_ACCEPT_ORDER",
                        "order_type":"2",
                        "order_sn":"20250508-152334-31583",
                        "return_store_info":
                            {
                                "store_addr_info":"山东省 德州市 宁津县德州市宁津县阳光大街南50米宁津县建设局-北门中心城区商业街影院广场东445号",
                                "store_mobile":"15305340559",
                                "store_name":"宁津极速鲜花店",
                                "accept_time":"1746694278"
                            }
                    }

                    */
               }


               huawaOrderInfo.setStatus(huawaStatus.getValue());
               huawaOrderInfoDao.updateObject(huawaOrderInfo);
           }else {
               log.warn("花娃订单信息不存在 json={}",data.toJSONString());
           }
        }else{
            log.warn("花娃订单状态异常 order_state={}",order_state);
        }


    }

    // 花店接单
    public void onStoreAcceptOrder(HuawaOrderInfo huawaOrderInfo){



    }




    // 开始配送
    @Transactional(rollbackFor = Exception.class)
    public void onStartDeliveryOrder(HuawaOrderInfo huawaOrderInfo) {
        log.info("HuawaServiceImpl.onStartDeliveryOrder 花娃开始配送 orderNo={}，getHuawaOrderId={},getHuawaOrderSn={}",huawaOrderInfo.getOrderNo(),huawaOrderInfo.getHuawaOrderId(),huawaOrderInfo.getHuawaOrderSn());
        GetCourieInfoRequest request = new GetCourieInfoRequest();
        request.setOrder_id(huawaOrderInfo.getHuawaOrderId());
        OpenApiResponse response = request.doRequest();
        /**
         * {
         *   "data": {
         *     "result": 1,
         *     "data": {
         *       "lng": "112.99045011075215",
         *       "de_member_phone": "19937188003",
         *       "delivery_no": "",
         *       "de_member_name": "白春丽",
         *       "lat": "34.7517760773211",
         *       "platform": "self_distribution",
         *       "status": -1
         *     }
         *   },
         *   "code": 200,
         *   "message": ""
         * }
         *
         response:
         {"result":1,"data":{"de_member_name":"\u853a\u5c0f\u82b3","de_member_phone":"18622108216","lng":"116.348212","lat":"40.068583","delivery_no":"","platform":"self_distribution","status":-1}}
         *
         *
         * */
        String shipperName = "";   // 配送员
        String shipperPhone = "";  // 电话
        if(!response.isError){
            /**
             *
             {"result":1,"data":{"lng":"116.4404616885746","de_member_phone":"13691374095","delivery_no":"","de_member_name":"崔瑞英","lat":"39.88796200965952","platform":"self_distribution","status":-1}}
             * */
            log.info("response.toJSONString()={}",response.toJSONObject().toJSONString());
            JSONObject resultData = response.toJSONObject();
            if(resultData.getInteger("result") == 1){
                JSONObject data = resultData.getJSONObject("data");
                shipperName = data.getString("de_member_name");
                shipperPhone = data.getString("de_member_phone");

            }
        }
        log.info("HuawaServiceImpl.onStartDeliveryOrder 配送信息 orderNo={}，shipperName={},shipperPhone={}",huawaOrderInfo.getOrderNo(),shipperName,shipperPhone);
        // orderInfoService.onOrderInfoSendNow(huawaOrderInfo.getOrderNo(),shipperName,shipperPhone);
        orderInfoService.onHuawaOrderInfoSendPeisong(huawaOrderInfo.getOrderNo(),shipperName,shipperPhone);


        // 发送 activeMq 消息
        JSONObject data = new JSONObject();
        data.put("order_no",huawaOrderInfo.getOrderNo());
        data.put("shipperName",shipperName);
        data.put("shipperPhone",shipperPhone);
        JSONObject message = MqMessageBuilder.builder()
                .target(ActiveMqConstant.hua000_api_queue)
                .event(EventConstant.event_logistics_start)
                .data(data)
                .build();

        activeMqService.sendQueue(ActiveMqConstant.hua000_api_queue,message.toJSONString());


    }


    public void  onOrderStorePrice(HuawaOrderInfo huawa){
        log.info("花店报价，获取报价花店列表！");
        SelectStoreListRequest request = new SelectStoreListRequest();
        request.setOrder_id(huawa.getHuawaOrderId());
        OpenApiResponse response = request.doRequest();



    }

    // 花娃订单重新发送
    @Override
    public void orderReCreate(String orderNo, HuawaOrderInfoVo vo) {

    }
}
